package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;


import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class UserStatusApiImpl implements UserStatusApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存冻结操作
     *
     * @param userStatus
     * @return
     */
    @Override
    public String saveUserStatus(UserStatus userStatus) {
        Query query = Query.query(Criteria.where("userId").is(userStatus.getUserId()));
        UserStatus userStatus1 = mongoTemplate.findOne(query, UserStatus.class);
        if (userStatus1 != null) {
            return null;
        }

        mongoTemplate.save(userStatus);
        return userStatus.getUserId().toString();
    }

    /**
     * 查询个人冻结情况
     *
     * @param userId
     * @return
     */
    @Override
    public UserStatus queryUserStatusById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserStatus userStatus = mongoTemplate.findOne(query, UserStatus.class);
        if (userStatus == null) {
            return null;
        }
        return userStatus;
    }

    /**
     * 查询所有用户的冻结情况
     *
     * @param userIds
     * @return
     */
    @Override
    public List<UserStatus> queryUserStatus(List<Long> userIds) {
        Query query = Query.query(Criteria.where("userId").in(userIds));
        List<UserStatus> userStatuses = mongoTemplate.find(query, UserStatus.class);
        if (userStatuses == null) {
            return null;
        }
        return userStatuses;
    }


    /**
     * 解冻操作
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean deleteUserStatus(Long userId) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserStatus userStatus = mongoTemplate.findOne(query, UserStatus.class);
            if (userStatus == null) {
                return null;
            }
            mongoTemplate.remove(userStatus);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return false;
    }
}
